<template>
  <div class="register">
      <div class="registerContainer">
        <div class="getCode">
           
           <div class="telAndcode">
             <div class="fonts">
            <img src="@assets/images/phone.png" alt="" />
             <h3>绑定手机号</h3>
             <!-- <p @click="noRegister()">游客模式</p> -->
           </div>
             <div class="tel">
               <input type="tel" placeholder="请输入11位手机号码" class="telInput" maxlength="11"  v-model="tel" > 
             </div>
             
           </div>
           <div class="telAndcode">
             <div class="fonts">
            <img src="@assets/images/yanzheng.png" alt="" />
             <h3>验证码</h3>
             <!-- <p @click="noRegister()">游客模式</p> -->
           </div>
             <div class="code">
                <input type="tel" placeholder="请输入短信验证码" @input="setButtonStatus" class="codeInput" maxlength="6" v-model="code"  >
                 <!--   -->
                <!-- <span class="sendCode" @click="sendCode()"   v-if="sending" :disabled="isDisabled" >发送验证码</span> -->
                <div class="sendCode" v-if="sending">
                  <img @click="sendCode()" src="@assets/images/sendcode.png" alt="">
                </div>
                <span class="sendagin" v-else>再次发送{{second}}</span> 
                <!-- <span class="secondVal"  v-else></span> -->
             </div>
             
           </div>
        </div>
        <div class="tips">
          <p>绑定说明:</p>
          <p>1、听见广播老用户绑定手机号码后,可同步共享APP内账户信息。</p>
          <p style="margin-bottom:0.8rem;">2、新用户绑定手机号码后，可通过手机号码登录听见广播APP后，同步微信端账户信息</p>
        </div>
        <div class="realRegister">
          <p  v-if="!isdis"  >
              <img src="@assets/images/sure2.png" alt=""  > 
          </p>
          <p  @click="realRegister()" v-if="isdis">
              <img src="@assets/images/sure.png" alt=""  > 
          </p>       
        </div>
      </div>

  </div>
</template>

<script>
// import { Toast } from 'mint-ui';
import sendVerifyCode from "@mixins/SendVerifyCode";
import {
  login,
  loginMobile,
  registerVerify,
  register,
  getCodeApi
} from "@api/user";
import attrs, { required, alpha_num, chs_phone } from "@utils/validate";
import { validatorDefaultCatch } from "@utils/dialog";
import { getLogo } from "@api/public";
import dayjs from "dayjs";
import { isWeixin } from "@utils";
import cookie from "@utils/store/cookie";
import { VUE_APP_API_URL } from "@utils";
import cbct from '../../assets/js/common/base.js';
import qs from 'qs';
import http from '../../assets/js/common/http.js'
import axios from 'axios';
import  base  from "@common/base";
// import { baseuserinfo } from "@api/cutPrice";
import {
  postCartAdd,
} from "@api/store";
import {wxCallback,getOpenId} from "@api/order";
const BACK_URL = "login_back_url";
const OID ='OID';

export default {
  name: 'Login',
  mixins: [sendVerifyCode],
  data(){
    return{
      isDisabled:false,
      isdis:false,
      sending:true,
      second:60,
      tel:'',
      code:'',
      returnUrl:'',
      is_live:'',
      chnnelId:'',
      a:'',
      current: 1,
      account: "",
      password: "",
      captcha: "",
      formItem: 1,
      type: "login",
      logoUrl: "",
      keyCode: "",
      codeUrl: "",
      codeVal: "",
      isShowCode: false,
      wxUrl:'',
      wxCode:'',
      isOpendId:'',
      oId:'',
      uri:'',
      local:'',
    }
  },
  beforeRouteEnter (to, from, next){
    next(vm => {
      // 通过 `vm` 访问组件实例,将值传入fromPath
      // alert(from.path);
      vm.uri = from.path
    })
  },
  methods:{
    getUrlCode (name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
    },
    setButtonStatus() {
      if(this.code == '' || this.tel =='') {
        this.isdis = false;
      }else{
        this.isdis=true;
      }
    },
    getCode () { // 非静默授权，第一次有弹框
      const code = this.getUrlCode('code') // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
      // this.uri =  document.referrer;
        // let removeLocalStorage =decodeURIComponent(window.location.href)
        //   console.log(removeLocalStorage)
        //   console.log(removeLocalStorage.split('cutUrl')[0])
        //   console.log(removeLocalStorage.split('cutUrl')[1])
        //   console.log(removeLocalStorage.split('cutUrl')[0].indexOf('cutPrice'))
        //   if(removeLocalStorage.split('&cutUrl=')[0].indexOf('cutPrice')!= '-1'){
        //       localStorage.clear();    
        //   }
      if(this.uri==''){
       //this.local='http://ds.h5.cbct.cn/login'
      this.local=window.location.href+'?detailId='+cookie.get("detailId")+'&mer_id='+cookie.get("mer_id")+'&uniqueId='+cookie.get("uniqueId")+'&secKillId='+cookie.get("secKillId")+'&loginType='+cookie.get("loginType")+'&cartNum='+cookie.get("cartNum")+'&cutUrl='+encodeURIComponent(localStorage['cutUrl'])
      }else{
        const arrurl = this.uri.split('/');
        // console.log(arrurl[arrurl.length-1]);
       this.local = arrurl[arrurl.length-1]+'?detailId='+cookie.get("detailId")+'&mer_id='+cookie.get("mer_id")+'&uniqueId='+cookie.get("uniqueId")+'&secKillId='+cookie.get("secKillId")+'&loginType='+cookie.get("loginType")+'&cartNum='+cookie.get("cartNum")+'&cutUrl='+encodeURIComponent(localStorage['cutUrl'])
      }
      
      if (code == null || code === '') {
        // console.log(cbct.DsAppId());
          window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+cbct.DsAppId()+'&redirect_uri=' + encodeURIComponent(this.local) + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'
      } else {
        this.wxCode=code;
        this.wxCallback1()
      }
    },
        //回传code
    wxCallback1(){
      wxCallback(this.wxCode).then(res => { 
          // console.log(res)
         cookie.set(OID, res.data.oId);    
        })
        .catch(res => {
          this.$dialog.error(res.msg);
        });
    },
    sendCode(){
      if (!this.sending) {
        return
      }
      let self=this;
      var reg=/^1\d{10}$/;
      if (this.tel=='' || this.tel==undefined) {
          return this.$dialog.toast({mes:"请输入手机号"});
           this.sending=true;
           this.isDisabled=true;
           return;
      }else if(!reg.test(this.tel)) {
          return this.$dialog.toast({mes:"请输入正确的手机号"});
           this.sending=true;
           this.isDisabled=true;
           return;
      }else{
        this.sending=false;
        this.isDisabled=true;
        this.timeDown();
        let self=this;
        http.post(cbct.https()+'/v2/jubilee/send-code', qs.stringify({
            mobile:this.tel
        })).then((response)=>{
            if(response.c == cbct.code.successRes){ 
               this.$dialog.toast({mes:"发送成功"});
            }else{
               this.$dialog.toast({mes:response.m});
            }
            
         }
        ).catch((error)=>{})
      }
    },
    realRegister(){
      let that=this;

      var obj={
        mobile:this.tel,
        code:this.code,
        oId:cookie.get(OID),
      }
      if (isWeixin()) {
        if(this.$route.query.cutUrl){
            let isPub = decodeURIComponent(this.$route.query.cutUrl);
            console.log(isPub)
            if(isPub.indexOf('cutPrice')!= '-1'&&isPub!=''){
              console.log('pub')
               this.$set(obj,'pub','1');
            }
        }
        this.$set(obj,'is_login','wxlogin');
      }else{
         this.$set(obj,'is_login','');
      }
        http.post(cbct.https()+'/ds/login-mobile', qs.stringify(obj)).then((res)=>{
              if(res.c == cbct.code.successRes){ 
                  let data = res.d.ds;
                  cbct.setCookie('token', res.d.app.token);
                  cbct.setCookie('salt', res.d.app.salt);
                  that.isOpendId =data.is_openid;
                  let newTime = Math.round(new Date() / 1000);
                  that.$store.commit(
                    "LOGIN",
                    data.token,
                    
                  );
                  this.$store.dispatch('cut/userInfo')
                  //  baseuserinfo().then(res => {
                  //   cbct.setCookie('cutUid', res.data.uid);
                  //   cookie.set("avatar", res.data.avatar);
                  // });
                  const backUrl = cookie.get(BACK_URL) || "/";
                  cookie.remove(BACK_URL);
                   if (isWeixin()){
                    
                      console.log(this.$route.query.cutUrl)
                      if(this.$route.query.cutUrl){
                        let uBack = decodeURIComponent(this.$route.query.cutUrl);
                        console.log(uBack)
                        console.log(uBack.split('cn/')[0])
                        console.log(uBack.split('cn/')[1])
                        if(uBack.indexOf('cutPrice')!= '-1'){
                            that.$router.replace({ path: uBack.split('cn/')[1] });
                            return
                        }
                    }
                      console.log('this.$route.query.loginType==='+this.$route.query.loginType)
                      cbct.setCookie('mer_id', this.$route.query.mer_id);
                      cbct.setCookie('detailId', this.$route.query.detailId);
                      cbct.setCookie('from1', 'H5');
                      if(this.$route.query.loginType == '0'){
                        that.$router.push({ path: "/detail/" + cookie.get("detailId")});
                      }else{
                        let q = {
                          productId: this.$route.query.detailId.split('?')[0],
                          cartNum: this.$route.query.cartNum,
                          new: 1,
                          secKillId:this.$route.query.secKillId,
                          mer_id:that.$route.query.mer_id,
                          uniqueId:this.$route.query.uniqueId
                        };
                        postCartAdd(q)
                          .then(function(res) {
                            if (isWeixin()) {
                             window.location.href = base.DsApiUrl()+"/order/submit/" + res.data.cartId+'?mer_id='+that.$route.query.mer_id;
                            }else{
                              that.$router.push({ path: "/order/submit/" + res.data.cartId+'?mer_id='+that.$route.query.mer_id});
                            }
                          })
                          .catch(res => {
                            console.log('res==='+res)
                            that.$router.push({ path: "/detail/" + cookie.get("detailId")});
                            return that.$dialog.toast({ mes: res.msg });
                          });
                      }
                   }else{
                      that.$router.replace({ path: backUrl });
                   }
                 
                }else{
               this.$dialog.toast({mes:res.m});
            }
            
        }
        ).catch((error)=>{console.log(error);})
        
    },
    timeDown(){
        this.isDisabled=true;
        let result=setInterval(()=>{
        --this.second;
        if (this.second<0) {
          clearInterval(result);
          this.sending=true;
          this.isDisabled=false;
          this.second=60;
        }
      },1000)
    },
    
  },
  created(){
    // alert(123);
    // const backUrl = cookie.get(BACK_URL) || "/";
    // alert(backUrl);
    // alert(backUrl.indexOf('\"'));
    // if(backUrl.indexOf('\"')!= '-1'){
    //   backUrl = backUrl.split('\"')[1];
    // }
    window.removeEventListener('popstate', window.popstate);
      axios.defaults.headers = {
        'Content-Type':'application/x-www-form-urlencoded',
      };
      axios.post(cbct.https()+'/admin/time', {  
        }).then(function (response) {
          if(response.data.c == cbct.code.successRes){
            var timing = response.data.d.time - Date.parse(new Date());                
            cbct.setCookie('timing',timing);
          }
        })
    if (isWeixin()) {
      this.wxUrl=window.location.href;
      if(this.isOpendId==0 && this.isOpendId==''){
        this.getCode()
      }
    }
  },
  watch:{
    tel(n,o){
      var reg=/^1\d{10}$/
      if (n=='' || n== undefined || n==null) {
        this.isdis=false;
      }else if( !reg.test(n)){
        this.isdis=false;
      }else if(reg.test(n) != '' && this.code !=''){
        this.isdis=true;
      }
    },
    code(n,o){
       var reg=/^1\d{10}$/
       if (n=='' || n== undefined || n==null) {
        this.isdis=false;
      }else if( !reg.test(this.tel)){
        this.isdis=false;
      }
      else if(n != '' && reg.test(this.tel) !=''){
        this.isdis=true;
      }

    }

  },
  mounted(){
    
  
  },
  components: {
  },
  // asda
}


</script>
<style scoped lang="scss">
  // html,body{
  //   // background-color: #fff;
  //   background: #fff;
  //   width:100%;
  //   height:100%;
  // }
   .register{
      // width: 100%;
      // height: 100%;
       overflow: hidden;
      box-sizing: border-box;
       position: absolute;
        width: 100%;
        min-height: 100%;
        top: 0;
        left: 0;
        // overflow-y: hidden;
        background-color: #fff;
      // background: #fff;
    // background-color: rgba(0, 0, 0, 0.2);
    // background: rgba(255, 255, 255, 0.3);




      .registerContainer{
        width: 100%;
        min-height: 100%;
        box-sizing: border-box;
        padding:0 0.74rem;
        background-color: #fff;

        // padding-bottom: 1.68rem;
        .getCode{
          .telAndcode{
            font-size: 0.24rem;

            .fonts{
              display: flex;
              align-items: center;
              // justify-content: space-between;
              // margin-bottom: 0.28rem;
              margin-top: 0.7rem;
              h3{
                font-size: 0.3rem;
                font-family:PingFangSC-Semibold,PingFang SC;
                font-weight:bold;
                color:rgba(51,51,51,1);
                // margin: 0.46rem 0;
                margin-left: 0.22rem;
              }
              img{
                width:0.48rem;
                height:0.48rem;
              }
              p{
                font-size: 0.24rem;
              }

            }
            .tel ,.code{
              width: 100%;
              height: 0.94rem;
              // margin-left: 5%;
              margin-bottom: 0.52rem; 
                border-bottom: 0.02rem solid #E4E4E4;

              // padding-bottom: 0.18rem;
              // padding:0.28rem 0;
             
            }
            .code{
              position: relative;
              // line-height: 0.94rem;
              // padding-bottom: 0.18rem;
              // display: 
              .codeInput{
                padding-right: 1.7rem;
                box-sizing: border-box;
                margin-bottom: 0.6rem;
                // vertical-align: middle;

              }
              span{
                  position:absolute;
                  display: block;
                  width: 30%;
                  height: 0.7rem;
                  right:2px;
                  top:2px;
                  line-height:0.7rem;
                }
              // .sendCode{
              //   position: absolute;
              //   display: flex;
              //   // background:rgba(204,50,50,1);
              //   top: 0;
              //   right: 0;
              //   color: #C93333;
              //   width:1.98rem;
              //   height: 0.56rem;
              //   border-radius:0.28rem;
              //   border:0.02rem solid rgba(201,51,51,1);
              //   // line-height: 0.56rem;
              //   align-items: center;
              //   justify-content: center;
              //   vertical-align: middle;


              // }
              .sendCode{
                width: 1.98rem;
                // height: 0.56rem;
                height: 0.94rem;
                position: absolute;
                display: inline-flex;
                // background:rgba(204,50,50,1);
                // top: 0.17rem;
                right: 0;
                align-items: center;

                img{
                  width: 1.98rem;
                  height: 0.56rem;
                }

              }
              .sendagin{
                line-height: 0.94rem;
              }

            }
             input{
                width: 100%;
                // padding: 0.18rem 0;
                // padding-left: 0.2rem;
                // padding-right: 180px;
                height: 100%;
                box-sizing: border-box;
                // border:1px solid  rgba(151,151,151,1);
                outline: none;
                // border-radius: 3px;
                border:none;
                // border-bottom: 0.02rem solid #E4E4E4;
                background: rgba(255, 255, 255, 0.3);

            //  &:first-child{
            //    margin-top: 0.26rem;
            //  }
            }
          }
         
          // .telAndcode{
          //   font-size: 0.24rem;
            
           
            
            
          // //  .code{
          // //       position: relative;
                
          // //   }
          // }
        }
        .tips{
            // font-size: 0.3rem;
            text-align: left;
            // width: 100%;
            margin: auto;
            // font-size: 0.26rem;
            // margin: 0 5%;
            font-size:0.28rem;
            font-family:PingFangSC-Regular,PingFang SC;
            font-weight:400;
            color:rgba(51,51,51,0.7);
           
            p{
              margin-bottom: 0.12rem;
              line-height: 1.5;
              &:first-child{
              font-family:PingFangSC-Semibold,PingFang SC;
              font-weight:bold;
              color:rgba(51,51,51,1);
              font-size:0.3rem;
            }
          }
             

        }
        .realRegister{
          font-size: 0.28rem;
          // padding-bottom: 1.68rem;
          p{
            width: 100%;
            margin: auto;
            outline: none;
            margin-bottom: 0.44rem;
            &:last-child{
              margin-bottom:0px;
              padding-bottom: 1.68rem;
              

            }
            img{
              width: 100%;
              display: block;
              cursor: pointer;
            }
          }
        }
      


      }
    
     
   }
 
</style>

